Setup Backend - Cloud Functions


What are Firebase Cloud Functions?

Firebase Cloud Functions are serverless functions that run in the cloud in response to events triggered by Firebase features and HTTPS requests. Think of them as the backend server for your FireApp application that automatically scales and manages infrastructure for you.

Key Benefits:

  • Serverless Architecture: No need to manage servers or infrastructure
  • Auto-scaling: Automatically handles traffic spikes
  • Event-driven: Responds to database changes, user actions, and HTTP requests
  • Cost-effective: Pay only for execution time
  • Integrated: Works seamlessly with other Firebase services

How Cloud Functions Work in FireApp

FireApp's Cloud Functions serve as the complete backend infrastructure for your messaging application. Here's how they work:

1. Message Handling Pipeline

When a user sends a message in your app, the following happens:

  1. Message Creation: App writes message to Firebase Realtime Database
  2. Function Trigger: sendMessageNotification function automatically triggers
  3. Processing: Function processes message data, checks for blocked users
  4. Notification: Sends push notification to recipient's device
  5. Indexing: Indexes message for the recipient in userMessages node

2. Real-time Communication Flow

User A sends message → Firebase Database → Cloud Function → 
Push Notification → User B receives notification → App fetches message

3. Group Message Handling

For group messages, the system:

  • Uses Firebase Cloud Messaging (FCM) topics for efficient delivery
  • Indexes messages for each group member individually
  • Handles group events (user joins, leaves, admin changes)
  • Manages group permissions and blocked users

Key Functions Overview

Here are the main Cloud Functions powering your FireApp backend:

Message Functions

Function Name Trigger Purpose
sendMessageNotification New message in /messages/{messageId} Sends push notifications for private messages
sendMessagesForGroups New message in /groupsMessages/{groupId}/{messageId} Handles group message notifications and indexing
deleteMessage New request in /deleteMessageRequests/{messageId} Handles message deletion with time limits

👥 Group Management Functions

Function Name Trigger Purpose
participantAdded User added to /groups/{groupId}/users/{userId} Handles user addition to groups and group creation events
participantRemoved User removed from /groups/{groupId}/users/{userId} Manages user removal and automatic admin assignment
groupEvents New event in /groupEvents/{groupId}/{eventId} Broadcasts group events to all members

Call Functions

Function Name Trigger Purpose
sendNewCallNotification New call in /userCalls/{uid}/{callId} Sends call notifications including VoIP for iOS
indexNewCall New call in /newCalls/{toId}/{fromId}/{callId} Indexes calls and checks for blocked users

Authentication & Security Functions

Function Name Trigger Purpose
saveUidOnLogin User creation Maps phone numbers to user IDs for quick lookups
getVirgilJwt HTTPS callable Generates JWT tokens for end-to-end encryption

Setting Up Cloud Functions

{warning} if you did not deploy Cloud Functions you will see no users. more info

Prerequisites

  • Firebase Project: Must have a Firebase project with Realtime Database enabled
  • Billing Plan: Must be on Firebase Blaze (pay-as-you-go) plan
  • Node.js: Install Node.js LTS version from nodejs.org
  • Firebase CLI: Command-line tools for deployment

Step 1: Install Firebase CLI

Open your terminal/command prompt and run:

# For Windows/Linux
npm install -g firebase-tools

# For Mac (if permission issues)
sudo npm install -g firebase-tools

Step 2: Prepare Your Project Directory

  1. Create a new folder for your backend project
  2. Navigate to the folder using one of these methods:

Method 1: Windows Explorer Shortcut

  • Hold Shift and right-click in the Backend - Cloud Functions folder
  • Select "Open command window here" or "Open PowerShell window here"

Method 2: Address Bar Trick

  • Open the Backend - Cloud Functions folder
  • Click in the address bar and type cmd, then press Enter

image

Method 3: Manual Navigation

  • Open terminal/command prompt
  • Type cd followed by a space
  • Drag the Backend-Cloud Functions folder into the terminal
  • Press Enter

Step 3: Authenticate with Firebase

firebase login

This opens your browser to sign in to your Google account associated with your Firebase project.

Step 4: Initialize Functions

firebase init functions

Follow the prompts:

  1. Select your Firebase project
  2. Choose JavaScript as the language
  3. Choose No for ESLint
  4. Choose No for installing dependencies now

image

Step 5: Configure Package Name

Before deploying, you must update the package name:

  1. Open Backend - Cloud Functions/index.js in any text editor
  2. Find the line: const packageName = "com.packagename.app"
  3. Replace with your actual Android app package name

Step 6: Copy Function Files

Copy these files from Backend - Cloud Functions to the newly created functions directory:

  • index.js - Main functions file
  • push-token-sender.js - Handles push notifications
  • message-sender.js - Message delivery logic
  • generate-virgil-jwt.js - Encryption token generation
  • package.json - Dependencies configuration

Step 7: Install Dependencies

# Navigate to functions directory
cd functions

# Install required packages
npm install

Step 8: Deploy Functions

firebase deploy

Successful deployment should show all function names:

image

Handling Deployment Errors

If you encounter network errors during deployment:

  1. Check the error message in terminal
  2. Copy the suggested retry command
  3. Run the command to deploy only failed functions

image

{warning} You must be on the Firebase Blaze Plan to deploy Cloud Functions. The free Spark plan doesn't support Cloud Functions.

Testing & Debugging

Local Testing

Test functions locally before deployment:

# Install Firebase emulator
npm install -g firebase-tools

# Start emulator
firebase emulators:start --only functions,database

# Your functions will be available at:
# http://localhost:5001/your-project-id/us-central1/functionName

Function Logs

Monitor function execution and debug issues:

# View all function logs
firebase functions:log

# View logs for specific function
firebase functions:log --only sendMessageNotification

# View real-time logs
firebase functions:log --follow

Common Issues & Solutions

Deployment Issues

Issue Cause Solution
Functions not deploying Not on Blaze plan Upgrade to Firebase Blaze plan
Syntax errors during deploy JavaScript errors in code Check logs, fix syntax errors
Function timeout Function takes too long Optimize code or increase timeout
Permission errors Missing Firebase permissions Check IAM roles in Firebase console

Getting Help

When you encounter issues:

  • Check Firebase console logs for detailed error messages
  • Use console.log() statements for debugging
  • Refer to Firebase Functions documentation
  • Test functions locally using the Firebase emulator
  • Check Firebase status page for service issues

{info} Remember: Every change to your Cloud Functions requires redeployment using firebase deploy. Always test your changes thoroughly before deploying to production.


Quick Reference Commands

# Essential commands for daily use
firebase login                    # Authenticate
firebase deploy                   # Deploy all functions
firebase functions:log            # View logs
firebase functions:config:get     # View configuration
firebase emulators:start         # Start local emulator